<?php


namespace app\zyhsapi\controller\v1;


use app\common\lib\AliOss;
use app\zyhsapi\controller\ZyhsAuth;
use OSS\Core\OssException;

class Upload extends ZyhsAuth
{
    protected $pathType = [
        1 => 'zyhsapp/uploads/avatar', // 头像
    ];

    /**
     * 文件上传大小
     * @var int
     */
    protected $file_max_size = 2097152; // 1024*1024*2=2097152  2M

    /**
     * 图片上传
     * @return \think\response\Json
     */
    public function upload()
    {
        $type = input('type/d', 1);

        $path = $this->pathType[$type] ?? '';

        if (!$path)
        {
            return show(config('code.error'), '上传类型异常');
        }

        $file = request()->file('file');

        if (isset($file))
        {
            $config = ['size' => $this->file_max_size];
            // tp5 文件上传验证
            $info = $file->validate($config)->oss($path);
            if (!$info)
            {
                return show(10034, $file->getError());
            }
            // 获取文件名
            $filename = $info->get_filename();
            // 字符串方式上传图片
            $content = file_get_contents($info->get_tmpname());
            try
            {
                $aliOss = AliOss::getInstance();
                $aliOss->ossUpload($filename, $content);
                if (in_array($type, [3, 4, 5]))
                {   // 设置文件私有化
                    $aliOss->setFileAuthPri($filename);
                }
            }
            catch (OssException $e)
            {
                return show(10034, $e->getMessage());
            }
        } else
        {
            return show(10033, 'File is not exited.');
        }

        return show(config('code.success'), '上传成功', ['path' => $filename]);
    }
}
